﻿using InTheHand.Net;
using System.Text;

namespace MyTRCP.Common.Models
{
    public class BtDevInfo : BitWalkableObj
    {
        public byte NameLength { get; set; }
        public string Name { get; set; } = string.Empty;
        public byte[] MacAddress { get; set; } = new byte[6];
        public BtDevInfo() { }
        public BtDevInfo(byte[] data) : base(data) { }
        public BtDevInfo(string name, BluetoothAddress ba)
        {
            Name = name;
            NameLength = (byte)name.Length;
            MacAddress = ba.ToByteArray().SkipLast(2).ToArray();
        }
        public override BitWalker ReadFromBitWalker(BitWalker bw)
        {
            if (bw.RemainingByteLen < 7)
                throw new ArgumentException("字节数组长度过小（7）", nameof(bw));
            NameLength = (byte)bw.ReadBits(8);
            Name = Encoding.UTF8.GetString(bw.ReadBytes(NameLength));
            MacAddress = bw.ReadBytes(6);
            return bw;
        }

        public override BitWalker WriteToBitWalker(BitWalker bw)
        {
            byte[] nameBytes = Encoding.UTF8.GetBytes(Name);
            return bw.WriteBits(nameBytes.Length, 8).WriteBytes(nameBytes).WriteBytes(MacAddress);
        }
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Name);
            sb.Append('(');
            for (int i = MacAddress.Length - 1; i >= 0; i--)
            {
                sb.AppendFormat("{0:X2}", MacAddress[i]);
                if (i > 0)
                {
                    sb.Append(":");
                }
            }
            sb.Append(")");
            return sb.ToString();
        }
    }
}